<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/wellcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card>
       <!-- 警告信息提示区域 -->
       <el-alert title="注意：只允许为第三级分类设置相关参数！" type="warning" 
       :closable="false" show-icon>
       </el-alert>

       <!-- 商品选择区域 -->
       <el-row class="cate_opt">
           <el-col>
               <span>选择商品分类：</span>
               <!-- 级联选择框 -->
               <el-cascader expandTrigger='hover' clearable
                v-model="selectId"
                :options="cateList"
                :props="cateProps"
                @change="selectChange">
               </el-cascader>
           </el-col>
       </el-row>

       <!-- tab 导航区 -->
       <el-tabs v-model="activeName" @tab-click="handleClick">
        <!-- 东动态参数 -->
        <el-tab-pane label="动态参数" name="many">
            <el-button v-if="selectId.length === 3" type="primary" size="small" @click="paramsDialogVisible = true">添加参数</el-button>
            <el-button v-else type="primary" size="small" disabled>添加参数</el-button>
            <el-table :data="manyData" stripe border>
                <el-table-column type="expand">
                    <template v-slot="scope">
                        <el-tag v-for="(item,index) in scope.row.attr_vals" :key="index" closable @close="handleClose(index,scope.row)">
                            {{item}}
                        </el-tag>
                        <el-input class="input-new-tag" size="small"
                         v-if="scope.row.inputVisible" v-model="scope.row.inputValue" ref="saveTagInput"
                         @keyup.enter.native="handleInputConfirm(scope.row)" @blur="handleInputConfirm(scope.row)">
                        </el-input>
                        <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                    </template>
                </el-table-column>
                <el-table-column type="index"  label="#"></el-table-column>
                <el-table-column prop="attr_name" label="参数名称"></el-table-column>
                <el-table-column label="操作">
                    <template v-slot="scope">
                        <el-button size="mini" type="primary" icon="el-icon-edit" @click="editDialog(scope.row.attr_id)">编辑</el-button>
                        <el-button size="mini" type="danger" icon="el-icon-delete" @click="deltParams(scope.row.attr_id)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-tab-pane>
        <!-- 静态属性 -->
        <el-tab-pane label="静态属性" name="only">
            <el-button v-if="selectId.length === 3" type="primary" size="small" @click="paramsDialogVisible = true">添加参数</el-button>
            <el-button v-else type="primary" size="small" disabled>添加参数</el-button>
            <el-table :data="onlyData" stripe border>
                <el-table-column type="expand">
                    <template v-slot="scope">
                        <el-tag v-for="(item,index) in scope.row.attr_vals" :key="index" closable @close="handleClose(index,scope.row)">
                            {{item}}
                        </el-tag>
                        <el-input class="input-new-tag" size="small"
                         v-if="scope.row.inputVisible" v-model="scope.row.inputValue" ref="saveTagInput"
                         @keyup.enter.native="handleInputConfirm(scope.row)" @blur="handleInputConfirm(scope.row)">
                        </el-input>
                        <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                    </template>
                </el-table-column>
                <el-table-column type="index"  label="#"></el-table-column>
                <el-table-column prop="attr_name" label="参数名称"></el-table-column>
                <el-table-column label="操作">
                    <template v-slot="scope">
                        <el-button size="mini" type="primary" icon="el-icon-edit" @click="editDialog(scope.row.attr_id)">编辑</el-button>
                        <el-button size="mini" type="danger" icon="el-icon-delete"  @click="deltParams(scope.row.attr_id)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-tab-pane>
       </el-tabs>
    </el-card>

    <!-- 添加参数弹框 -->
    <el-dialog
      :title="'添加' + titleTxt"
      :visible.sync="paramsDialogVisible"
      width="50%"
      center :modal-append-to-body="false"
      :close-on-click-modal="false"
      @close="paramsDialogClose">
      <!-- 表单信息 -->
      <el-form :model="paramsForm" :rules="paramsFormRules"  ref="paramsFormRef" label-width="100px" class="demo-ruleForm">
        <el-form-item :label="titleTxt" prop="attr_name">
            <el-input v-model="paramsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="paramsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改弹框 -->
    <el-dialog
      :title="'修改' + titleTxt"
      :visible.sync="editDialogVisible"
      width="50%"
      center :modal-append-to-body="false"
      :close-on-click-modal="false"
      @close="editsDialogClose">
      <!-- 表单信息 -->
      <el-form :model="editForm" :rules="paramsFormRules"  ref="editFormRef" label-width="100px" class="demo-ruleForm">
        <el-form-item :label="titleTxt" prop="attr_name">
            <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
export default {
    name:'Params',
    data(){
        return {
            cateList:[],
            cateProps:{
                value:'cat_id',
                label:'cat_name',
                children:'children'
            },
            selectId:[],
            activeName:'many',
            manyData:[],
            onlyData:[],
            paramsDialogVisible:false,
            paramsForm:{
                attr_name:''
            },
            paramsFormRules:{
                attr_name: [
                    { required: true, message: '请输入参数名称', trigger: 'blur' }
                ],
            },
            editDialogVisible:false,
            editForm:{},
        }
    },
    created(){
        this.getCategories()
    },
    computed:{
        // 当前选的三级分类id
        cateId(){
            if(this.selectId.length ===3){
                return this.selectId[2]
            }
            return null;
        },
        // 消息弹出框标题
        titleTxt(){
            if(this.activeName === 'many'){
                return '动态参数'
            }else{
                return '静态属性'
            }
        }
    },
    methods:{
        // 获取分类数据
        async getCategories(){
            const {data:res} = await this.axios.get('categories');
            if(res.meta.status !==200){
                return this.$message.error('获取商品分类失败了~');
            }
            // console.log(res);
            this.cateList = res.data;
        },
        // 级联选择框发生变化
        selectChange(){
            this.getParamsData();
        },
        // tab 页签点击事件
        handleClick(){
            this.getParamsData();
        },
        // 获取分类参数数据
        async getParamsData(){
            // 判断选择的是不是第三级分类
            if(this.selectId.length !== 3){
                this.selectId = [];
                this.onlyData = [];
                this.manyData = [];
                return ;
            }
            // 根据选择的分类获取参数
            const {data:res} = await this.axios.get(`categories/${this.cateId}/attributes`,
            {params:{sel:this.activeName}});
            if(res.meta.status !==200){
                return this.$message.error('获取商品分类参数失败了~');
            }
            // console.log(res);
            res.data.forEach(item => {
                item.attr_vals = item.attr_vals?item.attr_vals.split(' ') : [];
                item.inputVisible = false;
                item.inputValue = '';
            });
            // console.log(res.data);
            if(this.activeName === 'many'){
                this.manyData = res.data;
            }else{
                this.onlyData = res.data;
            }
        },
        // 添加对话框关闭事件
        paramsDialogClose(){
            this.$refs.paramsFormRef.resetFields();
        },
        // 添加参数事件
        addParams(){
            this.$refs.paramsFormRef.validate(async valid =>{
                if(!valid) return;
                const {data:res} = await this.axios.post(`categories/${this.cateId}/attributes`
                ,{attr_name:this.paramsForm.attr_name,
                    attr_sel:this.activeName});
                if(res.meta.status !==201){
                    return this.$message.error('添加分类参数失败了~');
                }
                this.$message.success('添加分类参数成功了~');
                this.getParamsData();
            })
            this.paramsDialogVisible = false;
        },
        // 修改参数弹框事件
        async editDialog(attr_id){
            // console.log(attr_id);
            // 发送请求获取参数
            const {data:res} = await this.axios.get(`categories/${this.cateId}/attributes/${attr_id}`,
            {params:{attr_sel:this.activeName}});
            if(res.meta.status !==200){
                return this.$message.error('获取分类参数失败了~');
            }
            this.editForm= res.data;
            this.editDialogVisible = true;
        },
        // 修改弹框关闭事件
        editsDialogClose(){
            this.$refs.editFormRef.resetFields();
        },
        // 修改参数提交事件
        editParams(){
            this.$refs.editFormRef.validate(async valid =>{
                if(!valid) return;
                const {data:res} = await this.axios.put(`categories/${this.cateId}/attributes/${this.editForm.attr_id}`,
                {attr_name:this.editForm.attr_name,attr_sel:this.activeName});
                if(res.meta.status !==200){
                    return this.$message.error('修改分类参数失败了~');
                }
                this.$message.success('修改分类参数成功了~');
                this.getParamsData();
            })
            this.editDialogVisible = false;
        },
        // 删除分类
        deltParams(id){
            this.$confirm('此操作将永久删除该分类参数, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                const {data:res} = await this.axios.delete(`categories/${this.cateId}/attributes/${id}`);
                if(res.meta.status !==200){
                    return this.$message.error('获取商品分类参数失败了~');
                }
                this.getParamsData();
                this.$message({
                    type: 'success',
                    message: '删除成功!'
                });
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });          
            });
        },
        // handleClose(tag) {
        //     this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1);
        // },
        // 点击按钮切换文本框
        showInput(row) {
            row.inputVisible = true;
            // this.$nextTick(_ => {
            //     this.$refs.saveTagInput.$refs.input.focus();
            // });
            this.$nextTick(()=>{
                this.$refs.saveTagInput.$refs.input.focus();
            })
        },
        // 添加属性项后，发起请求，保存操作
        async saveAttrvals(row){
            const {data:res} = await this.axios.put(`categories/${this.cateId}/attributes/${row.attr_id}`,
            {attr_name:row.attr_name,attr_sel:this.activeName,attr_vals:row.attr_vals.join(' ')});
            // console.log(res);
            if(res.meta.status !==200){
                return this.$message.error('添加参数项失败了~');
            }
            this.$message.success('添加参数项成功了~');
        },
        // 文本框失去焦点或回车键按下
        handleInputConfirm(row) {
            // console.log('ok');
            if(row.inputValue.trim().length === 0){
                row.inputValue = '';
                row.inputVisible = false;
                return;
            }
            row.attr_vals.push(row.inputValue.trim());
            row.inputValue = '';
            row.inputVisible = false;

            this.saveAttrvals(row)
        },
        // tag标签关闭
        handleClose(i,row){
            row.attr_vals.splice(i,1);
            this.saveAttrvals(row);
        }
    }
}
</script>

<style lang="less" scoped>
.cate_opt{
    margin: 15px 0;
    .el-cascader{
        width: 50%;
    }
}
.input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }
.button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }
</style>